import router, { resetRouter } from './router'
import store from './store'
import Cookies from 'js-cookie'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { Message } from 'element-ui'
import { getToken, getAuditStatus } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/password', '/mobileLogin', '/register', '/appDownload', '/seekPassword'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  if(to.path!=='/system/withdrawal'){
    const wxInfo = JSON.parse(localStorage.getItem('wxUserInfo'))
    wxInfo && store.dispatch('user/removewxUserInfo')
  }
  if(to.path === '/register'){
    store.dispatch('user/resetToken')
    localStorage.clear()
  }
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()
  const hasRoles = store.getters.roles && store.getters.roles.length > 0
  const localRoles = JSON.parse(localStorage.getItem('roles')) && JSON.parse(localStorage.getItem('roles')).length > 0
  const auditStatus = getAuditStatus()
  if (hasToken && auditStatus === '2' && localRoles) {
    if (to.path === '/login' || to.path === '/password' || to.path === '/mobileLogin' || to.path === '/register') {
      // if is logged in, redirect to the home page
      next()
    } else {
      if (hasRoles) {
        next()
      } else {
        try {
          const roles = await store.dispatch('user/getInfo')
          const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
          router.addRoutes(accessRoutes)
          next({ ...to, replace: true })
          // next()
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
      next()
    }
  } else {
    if (auditStatus === '2' && !localRoles) {
      Message.error('无权限')
      await store.dispatch('user/resetToken')
    }
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      next({ path: '/login' })
    }
  }
  NProgress.done()
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
